/*
Timer related code. The timer runs at a set rate which doesn't
correspond to the PWM or clock rate. This allows both PWM and main
clock to be changed while also allowing things to happen at predetermined times
easily enough
*/

#include <p30F4011.h>
#include <libpic30.h>
#include "settings.h"
#include "AC-Controller.h"
#include "globals.h"

volatile unsigned int now, previous = 0;
volatile unsigned int startTime, totalTime, endTime=0; // For seeing how long things take inside the A/D conversion.

volatile unsigned int counter_16k = 0;		// 16 KHz counter
volatile unsigned int counter_motor_ctl = PERIOD_MOTOR_CTL;
volatile unsigned int counter_periodic = PERIOD_PERIODIC;
volatile unsigned int counter_debug = PERIOD_DEBUG;
volatile unsigned int counter_led = PERIOD_LED;
volatile unsigned long sys_ticks = 0; //global system ticks timer. Never gets reset. Just overflows after 74.5 hours

void __attribute__ ((__interrupt__)) __attribute__((no_auto_psv)) _T1Interrupt(void) {
	IFS0bits.T1IF = 0; //ack the timer interrupt

	//update all the counters;
	counter_16k++;
        sys_ticks++;
	counter_motor_ctl--;
	counter_periodic--;
	counter_debug--;
	counter_led--;
	

	//now check to see if it is time to do stuff
	if (!counter_motor_ctl) {
		ControllerState.MotorCtrl = 1;
		counter_motor_ctl = PERIOD_MOTOR_CTL;
	}
	if (!counter_periodic) {
		ControllerState.PeriodicTasks = 1;
		counter_periodic = PERIOD_PERIODIC;
	}
	if (!counter_debug) {
		ControllerState.SendDebug = 1;
		counter_debug = PERIOD_DEBUG;
	}
	if (!counter_led) { //once a second
		counter_16k = 0;
		STATUS_LED = !STATUS_LED; //toggle the LED
		if (OVER_CURRENT_TRIP_STATE == 1) { // if an overcurrent event has occurred...
			overCurrentHasOccurred = 1; 	
			//clear_oc();
		}
		counter_led = PERIOD_LED;
	}
}

//ok... not totally *timer* related but time related so it's close enough
//NOTE: This does nothing to reset the watchdog timer. So if you try to delay
//for longer than the timer and haven't disabled the watchdog you WILL have
//a bad time, mkay?
void delay_ms(unsigned int time) {
	unsigned long long temp;
	temp = dFcy;
	temp = temp * time;
	temp = temp / 1000ULL;
	__delay32((unsigned long)temp);
}